package code.coolbaby.basal.web.security;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jmesa.facade.TableFacade;
import org.jmesa.limit.Limit;
import org.jmesa.view.component.Row;
import org.jmesa.view.html.component.HtmlTable;
import org.springframework.beans.factory.annotation.Autowired;

import code.coolbaby.basal.entity.Role;
import code.coolbaby.basal.entity.User;
import code.coolbaby.basal.service.RoleManager;
import code.coolbaby.basal.service.UserManager;
import code.coolbaby.core.orm.Page;
import code.coolbaby.core.orm.PropertyFilter;
import code.coolbaby.core.utils.HibernateWebUtils;
import code.coolbaby.core.utils.JmesaUtils;
import code.coolbaby.core.utils.ServiceException;
import code.coolbaby.core.web.struts2.CRUDActionSupport;
import code.coolbaby.core.web.struts2.Struts2Utils;

/**
 * 用户管理Action.
 * 
 * 使用Struts2 convention-plugin Annotation定义Action参数.
 * 
 * @author Kanine
 */
@SuppressWarnings("serial")
@Results( { @Result(name = CRUDActionSupport.RELOAD, location = "user.action", type = "redirect") })
public class UserAction extends CRUDActionSupport<User> {

	@Autowired
	private UserManager userManager;

	@Autowired
	private RoleManager roleManager;

	// 基本属性
	private User entity;
	private Long id;
	private Page<User> page = new Page<User>(5);// 每页5条记录

	// 角色相关属性
	private List<Role> allRoles; // 全部可选角色列表
	private List<Long> checkedRoleIds; // 页面中钩选的角色id列表

	// 基本属性访问函数 //

	public User getModel() {
		return entity;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = userManager.get(id);
		} else {
			entity = new User();
		}
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Page<User> getPage() {
		return page;
	}

	// CRUD Action 函数 //

	@Override
	public String list() throws Exception {
		HttpServletRequest request = Struts2Utils.getRequest();
		List<PropertyFilter> filters = HibernateWebUtils.buildPropertyFilters(request);

		page = userManager.search(page, filters);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		allRoles = roleManager.getAll();
		checkedRoleIds = entity.getRoleIds();
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		// 根据页面上的checkbox 整合User的Roles Set
		HibernateWebUtils.mergeByCheckedIds(entity.getRoles(), checkedRoleIds, Role.class);

		userManager.save(entity);
		addActionMessage("保存用户成功");
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		try {
			userManager.delete(id);
			addActionMessage("删除用户成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage(e.getMessage());
		}
		return RELOAD;
	}

	/**
	 * 支持使用Jquery.validate Ajax检验用户名是否重复.
	 */
	public String checkLoginName() {
		HttpServletRequest request = Struts2Utils.getRequest();
		String loginName = request.getParameter("loginName");
		String oldLoginName = request.getParameter("oldLoginName");

		if (userManager.isLoginNameUnique(loginName, oldLoginName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		// 因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}

	/**
	 * 基于Jmesa表格API的查询方法，实现了数据库端分页，包含排序、过滤、导出.
	 */
	public String jmesa() {
		HttpServletRequest request = Struts2Utils.getRequest();
		List<PropertyFilter> filters = HibernateWebUtils.buildJmesaFilters(request);
		page = userManager.search(page, filters);

		TableFacade facade = JmesaUtils.buildTableFacade(page);
		facade = this.ornamentFacade(facade);
		Limit limit = facade.getLimit();
		if (limit.isExported()) {
			facade.render();
			return null;
		} else {
			facade = JmesaUtils.reOrnamentFacade(facade);
			HtmlTable table = (HtmlTable) facade.getTable();
			table.getTableRenderer().setWidth("600px");
			request.setAttribute("jmesaHtml", facade.render());
		}
		return "jmesa";
	}

	/**
	 * Jmesa表格标题、列名等属性的设置.
	 */
	private TableFacade ornamentFacade(TableFacade facade) {
		facade.setColumnProperties("id", "name", "loginName");
		facade.getTable().setCaption("用户信息列表");
		Row row = facade.getTable().getRow();
		row.getColumn(0).setTitle("id");
		row.getColumn(1).setTitle("姓名");
		row.getColumn(2).setTitle("登录名");
		return facade;
	}

	// 其他属性访问函数与Action函数 //

	public List<Role> getAllRoles() {
		return allRoles;
	}

	public List<Long> getCheckedRoleIds() {
		return checkedRoleIds;
	}

	public void setCheckedRoleIds(List<Long> checkedRoleIds) {
		this.checkedRoleIds = checkedRoleIds;
	}
}
